﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AntiObesity.Base;
using AntiObesity.Base.Managers;

namespace AntiObesity.Services
{
    [WebService(Namespace = "http://antiobesity-project.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class UserServices : System.Web.Services.WebService
    {
        [WebMethod]
        public bool Register(User user)
        {
            if (UserManager.Exists(user.Name))
                return false;
            UserManager.Persist(user);
            return true;
        }

        [WebMethod]
        public void UpdateInformation(User user, float weight, float height, float targetWeight)
        {
            var userInServer = UserManager.FindByID(user.ID);
            if (user==null)
                return;

            // do not change username & password (password can be changed only on the server):
            var oldUsername = userInServer.Name;
            var oldPassword = userInServer.Password;
            UserManager.Persist(user);
            if (user.Name != oldUsername || user.Password != oldPassword)
            {
                user.Name = oldUsername;
                user.Password = oldPassword;
                UserManager.Persist(user);
            }
            BodyHistoryManager.PersistHistory(user.ID, weight, height);
            TargetHistoryManager.PersistHistory(user.ID, targetWeight);
        }

        [WebMethod]
        public User GetUserById(string id)
        {
            var user = UserManager.FindByID(new Guid(id));
            return user;
        }

        [WebMethod]
        public User GetUser(string username, string password)
        {
            var user = UserManager.FindByName(username);

            if (user == null || user.Password!=password)
                return null;

            return user;
        }

    }
}
